package com.intelligent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.intelligent.entity.OperationLogs;
import com.intelligent.mapper.OperationLogsMapper;
import com.intelligent.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("logs")
public class logController {
    @Autowired
    private OperationLogsMapper operationLogsService;

    /**
     * 分页查询操作日志列表
     * @param current 当前页码
     * @param size 每页大小
     * @param keyword 关键词搜索（员工账号、操作内容）
     * @return 分页结果
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword) {

        try {
            // 构建查询条件
            LambdaQueryWrapper<OperationLogs> queryWrapper = new LambdaQueryWrapper<>();

            // 关键词搜索（员工账号或操作内容）
            if (StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> wrapper
                        .like(OperationLogs::getEmployeeAccount, keyword)
                        .or()
                        .like(OperationLogs::getOperationContent, keyword)
                        .or()
                        .like(OperationLogs::getOperator, keyword));
            }

            // 按操作时间倒序排列
            queryWrapper.orderByDesc(OperationLogs::getOperationTime);

            // 分页查询
            Page<OperationLogs> page = new Page<>(current, size);
            IPage<OperationLogs> result = operationLogsService.selectPage(page, queryWrapper);

            // 构建返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("records", result.getRecords());
            response.put("total", result.getTotal());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            response.put("pages", result.getPages());

            return Result.success(response);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询操作日志失败: " + e.getMessage());
        }
    }

    /**
     * 删除操作日志
     * @param id 日志ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        try {
            operationLogsService.deleteById(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除操作日志失败: " + e.getMessage());
        }
    }
}
